package com.xybian.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xybian.entity.SysUser;
import com.xybian.services.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户详细信息服务实现
 *
 * @author SongRenShuo
 * @date 2023-12-23
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 按用户名加载用户
     *
     * @param username 用户名
     * @return 用户详细信息
     * @throws UsernameNotFoundException 找不到用户名异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 从数据库查询校验
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName, username);
        SysUser sysUser = sysUserService.getOne(wrapper);

        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 授权
        List<String> authenticationList = new ArrayList<>();
        Integer userType = sysUser.getUserType();
        if (userType == 0) {
            authenticationList.add("admin");
            authenticationList.add("user");
        } else {
            authenticationList.add("user");
        }
        // 返回
        return new UserDetailsImpl(sysUser, authenticationList);
    }
}
